package com.toidep.activities;

import java.util.Random;

import org.json.JSONObject;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.StrictMode;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.toidep.R;
import com.toidep.api.ApiController;
import com.toidep.api.ParseJSON;
import com.toidep.base.BaseActivity;
import com.toidep.config.ConfigUtility;
import com.toidep.config.Constants;
import com.toidep.interfaces.ResponseListener;
import com.toidep.payment.PaymentControl;
import com.toidep.preference.SharePreference;
import com.toidep.utilities.DialogUtility;

public class RegisterActivity extends BaseActivity {

	private EditText edtUsername, edtPassword, edtPasswordAgain, edtEmail;
	private Button buttonRegister;
	private String textUsername, textPassword, textPasswordAgain, textEmail;
	private ProgressDialog progressDialog;
	
	private boolean keepDefaultText = false;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		
		ConfigUtility.getConfig(RegisterActivity.this);
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.activity_register);
		
		if (ConfigUtility.os_version > 10) {
			StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
			StrictMode.setThreadPolicy(policy);
		}
		
		initComponents();
				
	}
	
	private void initComponents() {
		edtUsername = (EditText) findViewById(R.id.regUsername);
		edtPassword = (EditText) findViewById(R.id.regPassword);
		edtPasswordAgain = (EditText) findViewById(R.id.regPasswordAgain);
		edtEmail = (EditText) findViewById(R.id.regEmail);
		buttonRegister = (Button) findViewById(R.id.buttonRegister);
		buttonRegister.setOnClickListener(onClickRegister);
		//#226 & 356 - start
		if(!keepDefaultText){
			edtUsername.setText("");
			edtPassword.setText("");
			edtPasswordAgain.setText("");
			edtEmail.setText("");
		}
		//#226 & 356- end
	}
	

	
	private static final String ALLOWED_CHARACTERS ="0123456789qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM";

	private String getRandomString(final int sizeOfRandomString) {
		final Random random = new Random();
		final StringBuilder sb = new StringBuilder();
		for (int i = 0; i < sizeOfRandomString; ++i)
			sb.append(ALLOWED_CHARACTERS.charAt(random
					.nextInt(ALLOWED_CHARACTERS.length())));
		return sb.toString();
	}
	
	private OnClickListener onClickRegister = new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			textUsername = edtUsername.getEditableText().toString();
			textPassword = edtPassword.getEditableText().toString();
			textPasswordAgain = edtPasswordAgain.getEditableText().toString();
			textEmail = edtEmail.getEditableText().toString();
			
			if (!isPasswordValid(textPassword, textPasswordAgain)) {
				DialogUtility.showDialogAlert(
						RegisterActivity.this, 
						"", 
						getString(R.string.text_password_not_match), 
						getString(R.string.label_close), 
						null);
				return;
			}
			
			if (!isCaptchaValid()) {
				DialogUtility.showDialogAlert(
						RegisterActivity.this, 
						"", 
						getString(R.string.text_captcha_not_match), 
						getString(R.string.label_close), 
						null);
				return;
			}
			
			if(!isValidEmail(textEmail)){
				DialogUtility.showDialogAlert(
						RegisterActivity.this, 
						"", 
						"Bạn đã nhập email sai định dạng", 
						getString(R.string.label_close), 
						null);
				return;
			}
			doRegister(textUsername, textPassword, textEmail);
		}
	};
	
	private boolean isValidEmail(String target) {
		  if (TextUtils.isEmpty(target)) {
		    return false;
		  } else {
		    return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
		  }
		}
	
	private void setResultForFinish() {
		SharePreference sharePreference = SharePreference.getInstance(this);
		Intent intent = new Intent();
		if (sharePreference.getLoginStatus())
			setResult(1, intent);
		else
			setResult(0, intent);
		finish();
	}

	private void doRegister(final String username,final String password, final String email) {
		showProgressDialog();
		try {
			ApiController.register(RegisterActivity.this, username, password, email, new ResponseListener() {
				
				@Override
				public void processResponse(int inintstall) {
					closeProgressDialog();
					DialogUtility.showDialogAlert(RegisterActivity.this, 
							"", 
							getString(R.string.text_register_no_network), 
							getString(R.string.label_close), null);
				}
				
				@Override
				public void processResponse(String response) {
					Log.e("Register response", response);
					closeProgressDialog();
					// Ket noi thanh cong, lay code va message
					try {
						JSONObject jsonObject = new JSONObject(response);
						int code = ParseJSON.getIntValue(jsonObject , Constants.PARAM_RESPONSE_CODE);
						String message = ParseJSON.getStringValue(jsonObject , Constants.PARAM_RESPONSE_MESSAGE);
						if (code == 1) {
							// Dang ky thanh cong, lay access_token
							JSONObject data = new JSONObject(ParseJSON.getStringValue(jsonObject , Constants.PARAM_RESPONSE_DATA));
							String accessToken = ParseJSON.getStringValue(data , Constants.PARAM_RESPONSE_ACCESS_TOKEN);
//							DialogUtility.showDialogAlert(RegisterActivity.this, 
//									"", 
//									"access token: " + accessToken, 
//									getString(R.string.label_close), null);
							
							SharePreference ioeShare = SharePreference.getInstance(RegisterActivity.this);
							ioeShare.putLoginStatus(true);
							ioeShare.putUserName(username);
							ioeShare.putPassword(password);
							ioeShare.putUserEmail(email);
							ioeShare.putAccessToken(accessToken);
							
							afterRegister();		// @aTra: goi thanh toan
						} else {
							// Tai khoan da ton tai
							DialogUtility.showDialogAlert(RegisterActivity.this, 
									"", 
									message, 
									getString(R.string.label_close), null);
						}
					} catch (Exception e) {
						DialogUtility.showDialogAlert(RegisterActivity.this, 
								"", 
								getString(R.string.text_register_no_network), 
								getString(R.string.label_close), null);
					}
						
				}
			});
		} catch (Exception e) {
			// TODO: handle exception
		}
		
	}
	
	/**
	 * Dang ky thanh cong, goi thanh toan
	 */
	private void afterRegister() {
		PaymentControl paymentControl = new PaymentControl(this);
		paymentControl.setListener(new ResponseListener() {
			
			@Override
			public void processResponse(int inintstall) {
				if(inintstall==-1){
					SharePreference ioeShare = SharePreference.getInstance(RegisterActivity.this);
					ioeShare.putLoginStatus(false);
				}
				setResultForFinish();
			}
			
			@Override
			public void processResponse(String response) {
				setResultForFinish();
			}
		});
		
		paymentControl.showDialogPaymentStart();
	}
	
	/*
	 * Kiem tra du lieu dau vao
	 */
	private boolean isPasswordValid(String pwd, String pwdAgain) {
		boolean valid = true;
		if (pwd.equals(pwdAgain) == false)
			valid = false;
		return valid;
	}
	
	private boolean isCaptchaValid() {
		return true;
	}
	
	// Show/hide Progress Dialog
	public void showProgressDialog() {
		if (progressDialog == null) {
			progressDialog = ProgressDialog.show(this, null, getResources().getString(R.string.text_processing), true);
			progressDialog.setCancelable(false);
		}
	}

	public void closeProgressDialog() {
		if (progressDialog != null) {
			progressDialog.cancel();
			progressDialog = null;
		}
	}
}
